<template>
  <el-select
    style="width: 100%"
    size="mini"
    :value="value"
    clearable
    filterable
    :disabled="disabled"
    :placeholder="placeholder"
    remote
    reserve-keyword
    loading-text="正在加载…"
    :remote-method="getCompanyList"
    :loading="companyListLoading"
    @input="change($event)">
    <el-option
      v-for="item in companyList"
      :key="item.companyId"
      :label="item.companyName"
      :value="item.companyId">
      <span style="float: left">{{ item.companyName }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px;">{{ item.address }}</span>
    </el-option>
  </el-select>
</template>

<script>
  import { getCompanyList } from '@/utils/common'
  export default {
    name: 'company-select',
    props: {
      value: {
        type: String
      },
      keyword: {
        type: String
      },
      disabled: {
        type: Boolean,
        default: false
      },
      placeholder: {
        type: String,
        default: '请输入公司名关键字搜索'
      }
    },
    data () {
      return {
        companyList: null,
        companyListLoading: false,
        selectvalue: ''
      }
    },
    created () {
      this.getCompanyList(this.keyword)
    },
    methods: {
      change: function (val) {
        this.$emit('input', val)
        this.$emit('changeFunction', val)
      },
      getCompanyList: function (keyword) {
        var numReg = new RegExp(/^[0-9]+$/)
        // 触发查询的前提是：非数字一个字符以上，如果是纯数字，3个数字以上
        if (keyword && ((keyword !== '' && (!numReg.test(keyword))) || (numReg.test(keyword) && keyword.length >= 3))) {
          this.companyListLoading = true
          getCompanyList(keyword).then(({data}) => {
            this.companyListLoading = false
            this.companyList = data.companyList
          })
        } else {
          this.companyList = []
        }
      }
    }
  }
</script>
